﻿namespace Refract.Event
{
    using System;

    using Refract.Composition;

    /// <summary>
    /// Creates a subscription to a Notification. 
    /// </summary>
    /// <remarks>
    /// This maintains a strong reference to the delegate in order to keep the delegate alive while the delegate's source is alive.
    /// This object should be referenced only by the delegate's source to prevent memory leaks.
    /// </remarks>
    /// <typeparam name="TParam">The type of the param.</typeparam>
    public class NotificationSubscription<TParam>
    {
        #region Fields

        private EventHandler<EventArgs<TParam>> _handler;

        #endregion Fields

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="NotificationSubscription&lt;TParam&gt;"/> class.
        /// </summary>
        /// <param name="notificationName">Name of the notification.</param>
        /// <param name="handler">The handler.</param>
        public NotificationSubscription(string notificationName, EventHandler<EventArgs<TParam>> handler)
        {
            _handler = handler;
            Notification<TParam> notification = Container.Current.GetExportedValue<Notification<TParam>>(Notification.QualifiedName(notificationName));
            notification.Subscribe(_handler);
        }

        #endregion Constructors
    }

    /// <summary>
    /// Creates a subscription to a Notification.
    /// </summary>
    public class NotificationSubscription : NotificationSubscription<object>
    {
        #region Constructors

        public NotificationSubscription(string notificationName, EventHandler<EventArgs<object>> handler)
            : base(notificationName, handler)
        {
        }

        #endregion Constructors
    }
}